<?php if ( ! defined('BASEPATH')) exit('No se permite acceso directo vía scripts');
/**
 * Created by IntelliJ IDEA.
 * User: Luciano
 * Date: 31/10/13
 * Time: 13:41
 */

class Usuario extends CI_Controller{

	function __construct(){
		parent::__construct();
		$this->load->model('usuario_model');
		$this->load->library('encrypt');
		//$this->load->library('persona');
	}
	public function index(){
		if($this->session->userdata('ingresado')){
			//ingresado
			$data['title'] = 'Usuarios';
			$data['main_content'] = 'usuario/index';
			$this->load->view('main_template',$data);
		}else{
			$data['title'] = 'Inicio de sesión';
			$data['main_content'] = 'usuario/login';
			$this->load->view('main_template',$data);
		}
	}

	public function alta(){
		/*$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<em>','</em>');
		if($this->form_validation->run() == FALSE){
			//Falta el aviso
			$this->index();
		}else{*/
		$this->load->view('usuario/alta');
	}

	public function login(){
		/**
		 * Falta:
		 * 		Mensajes de error
		 */
		$request_method = $_SERVER["REQUEST_METHOD"];
		if($request_method == "GET"){
			if($this->session->userdata('ingresado')){
				//ingresado
			}else{
				$data['title'] = 'Inicio de sesión';
				$data['main_content'] = 'usuario/login';
				$this->load->view('main_template',$data);
			}
		}elseif ($request_method == "POST"){
			$this->load->model('usuario_model');
			if($this->usuario_model->login($_POST['user'],$_POST['password'])){
				$data=$this->usuario_model->buscarUser($_POST['user']);
				$data->ingresado=true;
				$this->session->set_userdata($data);
				$this->index();
			}else{
				//Falta el aviso
				//$this->session->set_flashdata('usuario_incorrecto','Los datos introducidos son incorrectos.');
				$this->index();
			}
		}
	}
	public function logout(){
		if($this->session->userdata('ingresado')){
			//ingresado
			$this->session->sess_destroy();
			$this->load->library('../controllers/welcome');
			$this->welcome->index();
		}else{
			$data['title'] = 'Inicio de sesión';
			$data['main_content'] = 'usuario/login';
			$this->load->view('main_template',$data);
		}
	}
}